package process

import (
	"errors"
	"github.com/astaxie/beego"
	"public_security/databases"
	"public_security/models"
)

func Create(req *models.Process) error {
	var count int
	databases.DbDefault.Model(&models.Process{}).Select("count(id)").Where("process_time=date_format(now(), '%Y-%m-%d')").Scan(&count)
	if count > 0 {
		return errors.New(req.ProcessTime + "已经排班，请勿重复排班")
	}
	req.Status = 2
	if err := databases.DbDefault.Model(&models.Process{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func Update(req *models.Process) error {
	if err := databases.DbDefault.Model(&models.Process{}).Where("id=?", req.Id).Updates(map[string]interface{}{
		"leader":      req.Leader,
		"police":      req.Police,
		"clerk":       req.Clerk,
		"woman_clerk": req.WomanClerk,
		"status":      req.Status,
		"sort":        req.Sort,
	}).Error; err != nil {
		return err
	}
	if req.Sort == 1 {
		databases.DbDefault.Model(&models.Process{}).Where("is_check=1").Update("is_check", 2)
		databases.DbDefault.Model(&models.Process{}).Where("id=?", req.Id).Update("is_check", 1)
	}
	return nil
}

func Remove(req *models.Process) error {
	var count int
	databases.DbDefault.Model(&models.Process{}).Select("count(id)").Where("id=? and status=2", req.Id).Scan(&count)
	if count > 0 {
		return errors.New("已上架的排班，不支持删除")
	}
	if err := databases.DbDefault.Model(&models.Process{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func Query(req *models.Process) []*models.Process {
	arts := make([]*models.Process, 0)
	db := databases.DbDefault.Model(req)
	if beego.AppConfig.String("Mode") == "web" {
		db.Where("is_check=1").Find(&arts)
	} else {
		db.Order("process_time asc").Find(&arts)
	}
	return arts
}
